package com.fh.controller.ccode.system;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.tools.Tool;

import org.apache.james.mime4j.field.datetime.DateTime;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fh.controller.base.BaseController;
import com.fh.service.ccode.AppCcodeUserService;
import com.fh.util.AliSmsUtil;
import com.fh.util.AppUtil;
import com.fh.util.PageData;
import com.fh.util.Tools;
import com.fh.util.UuidUtil;
import com.sun.xml.internal.bind.v2.model.core.ID;
import com.taobao.api.ApiException;

import oracle.net.aso.a;

@Controller
@RequestMapping(value="/appsystem")
public class LoginRegisterController extends BaseController{
	
	@Resource(name="appCcodeUserService")
	private AppCcodeUserService appCcodeUserService;

	/**
	 * 请求登录，验证用户
	 */
	@RequestMapping(value="/sys_login" ,produces="application/json;charset=UTF-8")
	@ResponseBody
	public Object login(HttpServletRequest request, HttpServletResponse response)throws Exception{
		response.setHeader("Access-Control-Allow-Origin","*");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String errInfo = "";
		String codeInfo = "";
		String USERNAME = pd.getString("username");
		String PASSWORD  = pd.getString("password");
		
		if(USERNAME != null && PASSWORD != null){
			
			pd.put("USERNAME", USERNAME);
				
			String passwd = new SimpleHash("SHA-1", USERNAME, PASSWORD).toString();	//密码加密
			pd.put("PASSWORD", passwd);
			pd = appCcodeUserService.getUserByNameAndPwd(pd);
			if(pd != null){
				
				//shiro加入身份验证
				Subject subject = SecurityUtils.getSubject(); 
			    UsernamePasswordToken token = new UsernamePasswordToken(USERNAME, PASSWORD); 
			    try { 
			        subject.login(token); 
			    } catch (AuthenticationException e) { 
			    	errInfo = "身份验证失败！";
			    }
			}
			else{
				errInfo = "用户名或密码错误"; 				//用户名或密码有误
				codeInfo = "F";
			}
				
			if(Tools.isEmpty(errInfo)){
				errInfo = "登录成功";					//验证成功
				codeInfo = "T";
				map.put("userid", pd.get("C_USER_ID"));
				
				String newToken = UuidUtil.get32UUID();
				System.out.println(newToken);
				pd.put("NEWTOKEN", newToken);
				appCcodeUserService.updateToken(pd);
				
				map.put("token", newToken);
				
			}
			
		}else{
			errInfo = "缺少参数";	//缺少参数
			codeInfo = "F";
		}
		map.put("msg", errInfo);
		map.put("code", codeInfo);
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 用户注册
	 */
	@RequestMapping(value="/register")
	@ResponseBody
	public Object Register(HttpServletRequest request, HttpServletResponse response)
	{
		response.setHeader("Access-Control-Allow-Origin","*");
		Map<String, Object> map = new HashMap<String , Object>();
		
		PageData pd = new PageData();
		pd = this.getPageData();
		String name = pd.getString("username");
		String pwd = pd.getString("password");
		String passwd = new SimpleHash("SHA-1", name, pwd).toString();	//密码加密
		String phone = pd.getString("phone");
		String code = pd.getString("vertifyNum");
		
		PageData temp = new PageData();
		
		temp.put("NAME", name);
		temp.put("PHONE", phone);
		temp.put("ROLE", pd.getString("role"));
		temp.put("PASSWORD", passwd);
		temp.put("EMAIL", pd.getString("email"));
		temp.put("CITY", pd.getString("city"));
		temp.put("DESCRIPTION", pd.getString("description"));
		temp.put("SEX", pd.getString("sex"));
		String token = UuidUtil.get32UUID();
		temp.put("TOKEN", token);
		System.out.println(token);
		
		temp.put("token", token);
		
		String checkResult;
		try {
			checkResult = checkCode(phone, code);
			// 不相等
			if(checkResult.equals("T") != true){
				map.put("code", "F");
				map.put("msg", checkResult);
			}else if(appCcodeUserService.findInfoByName(temp) != null){
				map.put("code", "F");
				map.put("msg", "用户名重复");
			}else if(appCcodeUserService.findInfoByPhone(temp) != null){
				map.put("code", "F");
				map.put("msg", "手机号重复");
			}else{
				// 保存用户信息
				appCcodeUserService.saveRegisterInfo(temp);
				pd.put("token", token);
				PageData pdData = appCcodeUserService.getInfoByToken(pd);
				map.put("code", "T");
				map.put("msg", "注册成功");
				map.put("userid", pdData.get("C_USER_ID"));
				map.put("token", token);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put("code", "F");
			map.put("msg", "注册失败");
		}
		
		return AppUtil.returnObject(new PageData(), map);
		
	}
	
	// 验证码正确与否判断函数
	@SuppressWarnings("unused")
	private String checkCode(String phoneNum,String code) throws Exception{
		PageData pd = new PageData();
		pd.put("phoneNum", phoneNum);
		pd.put("code", code);
		pd = appCcodeUserService.findValidateCode(pd);
		String trueCode = pd.getString("VALIDATE_CODE");
		Date codeTime = (Date) pd.get("GENERATE_TIME");
		// 计算时间差
		Date currTime = new Date();
		long minuteSpan = (codeTime.getTime() - currTime.getTime())/(1000*60);
		
		if(pd == null){
			return "未申请验证码";
		}else{
			// 判断过期
			if(minuteSpan > 60){
				return "验证码过期";
			}else{
				if(trueCode.equals(code)){
					return "T";
				}else{
					return "验证码错误";
				}
			}
		}
	}
	
	/**
	 * TEST 忘记密码
	 */
	@RequestMapping(value="/forget")
	@ResponseBody
	public Object ForgetPassWord(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		response.setHeader("Access-Control-Allow-Origin","*");
		Map<String, Object> map = new HashMap<String , Object>();
		
		PageData pd = new PageData();
		pd = this.getPageData();
		String name = pd.getString("username");
		String pwd = pd.getString("password");
		String passwd = new SimpleHash("SHA-1", name, pwd).toString();	//密码加密
		pd.put("passwordHash", passwd);
		String phone = pd.getString("phone");
		String code = pd.getString("vertifyNum");
		
		String checkResult;
		try {
			// 检查手机验证码是否正确
			checkResult = checkCode(phone, code);
			// 不相等
			if(checkResult.equals("T") != true){
				map.put("code", "F");
				map.put("msg", checkResult);
			}else{
				// 判断用户名手机存不存在,匹不匹配
				if(appCcodeUserService.existUserWithPhone(pd)){
					appCcodeUserService.changePassword(pd);
					map.put("code", "T");
					map.put("msg", "修改密码成功");
				}else{
					map.put("code", "F");
					map.put("msg", "用户名与手机号码不匹配");
				}		
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put("code", "F");
			map.put("msg", "修改密码失败");
			
		}
		
		return AppUtil.returnObject(new PageData(), map);
		
	}
	
	@RequestMapping(value="/getRole")
	@ResponseBody
	public Object getRole(HttpServletRequest request, HttpServletResponse response)
	{
		response.setHeader("Access-Control-Allow-Origin","*");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		try
		{
			pd = appCcodeUserService.getInfoByToken(pd);
			map.put("data", pd.get("ROLE").toString());
			map.put("code", "T");
			map.put("msg", "获取身份成功");
			
		}catch(Exception e){
			e.printStackTrace();
			map.put("code", "F");
			map.put("code", "获取身份失败");
		}
		
		
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 获取短信验证码
	 */
	@RequestMapping(value="/getPhoneCode")
	@ResponseBody
	public Object getPhoneCode(HttpServletRequest request, HttpServletResponse response)
	{
		response.setHeader("Access-Control-Allow-Origin","*");
		Map<String,Object> map = new HashMap<String,Object>();
		
		PageData pd = new PageData();
		pd = this.getPageData();
		String phoneNum = pd.getString("phoneNum");
		
		if(phoneNum == null){
			map.put("code", "F");
			map.put("msg", "手机未填写");
		}
		
		try
		{
			PageData origin = appCcodeUserService.findValidateCode(pd);
			// 生成Code
			String code = Tools.getRandomNum() + "";
			pd.put("code", code);
			if(origin == null){
				appCcodeUserService.insertValidateCode(pd);
			}else{
				appCcodeUserService.updateValidateCode(pd);
			}
			// 发送短信
			AliSmsUtil.sendSMS(phoneNum, code);
			
			map.put("code", "T");
			map.put("msg", "获取短信验证码成功");
			
		}catch(Exception e){
			e.printStackTrace();
			map.put("code", "F");
			map.put("code", "获取短信验证码失败");
		}
		
		
		return AppUtil.returnObject(new PageData(), map);
	}
}
